package com.zhentao.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.mapper.IncomeBillMapper;
import com.zhentao.mapper.ExpenseBillMapper;
import com.zhentao.mapper.AccountFlowMapper;
import com.zhentao.mapper.AdvanceReceiptBillMapper;
import com.zhentao.pojo.IncomeBill;
import com.zhentao.pojo.ExpenseBill;
import com.zhentao.pojo.AccountFlow;
import com.zhentao.pojo.AdvanceReceiptBill;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 财务报表管理接口
 */
@RestController
@RequestMapping("/finance/financialReport")
public class FinancialReportController {

    @Autowired
    private IncomeBillMapper incomeBillMapper;

    @Autowired
    private ExpenseBillMapper expenseBillMapper;

    @Autowired
    private AccountFlowMapper accountFlowMapper;

    @Autowired
    private AdvanceReceiptBillMapper advanceReceiptBillMapper;

    /**
     * 收支项明细查询
     * 查询收入单和支出单的明细情况，支持合计、打印和导出
     */
    @GetMapping("/incomeExpenseDetails")
    public Result<Map<String, Object>> getIncomeExpenseDetails(
            @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String billType,
            @RequestParam(required = false) Integer status) {

        Map<String, Object> result = new HashMap<>();
        
        // 查询收入单
        if ("income".equals(billType) || billType == null) {
            QueryWrapper<IncomeBill> incomeWrapper = new QueryWrapper<>();
            if (StringUtils.hasText(startDate)) {
                incomeWrapper.ge("create_time", startDate);
            }
            if (StringUtils.hasText(endDate)) {
                incomeWrapper.le("create_time", endDate);
            }
            if (status != null) {
                incomeWrapper.eq("status", status);
            }
            incomeWrapper.orderByDesc("create_time");
            
            Page<IncomeBill> incomePage = new Page<>(pageNum, pageSize);
            Page<IncomeBill> incomeResult = incomeBillMapper.selectPage(incomePage, incomeWrapper);
            result.put("incomeBills", incomeResult);
        }
        
        // 查询支出单
        if ("expense".equals(billType) || billType == null) {
            QueryWrapper<ExpenseBill> expenseWrapper = new QueryWrapper<>();
            if (StringUtils.hasText(startDate)) {
                expenseWrapper.ge("create_time", startDate);
            }
            if (StringUtils.hasText(endDate)) {
                expenseWrapper.le("create_time", endDate);
            }
            if (status != null) {
                expenseWrapper.eq("status", status);
            }
            expenseWrapper.orderByDesc("create_time");
            
            Page<ExpenseBill> expensePage = new Page<>(pageNum, pageSize);
            Page<ExpenseBill> expenseResult = expenseBillMapper.selectPage(expensePage, expenseWrapper);
            result.put("expenseBills", expenseResult);
        }
        
        return Result.success(result);
    }

    /**
     * 收付款明细查询
     * 查询收款单和付款单的明细情况，支持合计、打印和导出
     */
    @GetMapping("/paymentReceiptDetails")
    public Result<Map<String, Object>> getPaymentReceiptDetails(
            @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
            @RequestParam(name = "pageSize", defaultValue = "10") int pageSize,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String flowType,
            @RequestParam(required = false) String billType) {

        Map<String, Object> result = new HashMap<>();
        
        // 查询账户流水
        if ("flow".equals(billType) || billType == null) {
            QueryWrapper<AccountFlow> flowWrapper = new QueryWrapper<>();
            if (StringUtils.hasText(startDate)) {
                flowWrapper.ge("create_time", startDate);
            }
            if (StringUtils.hasText(endDate)) {
                flowWrapper.le("create_time", endDate);
            }
            if (StringUtils.hasText(flowType)) {
                flowWrapper.eq("flow_type", flowType);
            }
            flowWrapper.orderByDesc("create_time");
            
            Page<AccountFlow> flowPage = new Page<>(pageNum, pageSize);
            Page<AccountFlow> flowResult = accountFlowMapper.selectPage(flowPage, flowWrapper);
            result.put("accountFlows", flowResult);
        }
        
        // 查询收预付款单
        if ("receipt".equals(billType) || billType == null) {
            QueryWrapper<AdvanceReceiptBill> receiptWrapper = new QueryWrapper<>();
            if (StringUtils.hasText(startDate)) {
                receiptWrapper.ge("create_time", startDate);
            }
            if (StringUtils.hasText(endDate)) {
                receiptWrapper.le("create_time", endDate);
            }
            receiptWrapper.orderByDesc("create_time");
            
            Page<AdvanceReceiptBill> receiptPage = new Page<>(pageNum, pageSize);
            Page<AdvanceReceiptBill> receiptResult = advanceReceiptBillMapper.selectPage(receiptPage, receiptWrapper);
            result.put("receiptBills", receiptResult);
        }
        
        return Result.success(result);
    }

    /**
     * 利润报表
     * 统计收入、支出金额和具体信息，计算利润
     */
    @GetMapping("/profitReport")
    public Result<Map<String, Object>> getProfitReport(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String groupBy) {

        Map<String, Object> result = new HashMap<>();
        
        // 统计收入
        QueryWrapper<IncomeBill> incomeWrapper = new QueryWrapper<>();
        incomeWrapper.eq("status", 1); // 只统计已审核的收入
        if (StringUtils.hasText(startDate)) {
            incomeWrapper.ge("create_time", startDate);
        }
        if (StringUtils.hasText(endDate)) {
            incomeWrapper.le("create_time", endDate);
        }
        incomeWrapper.select("IFNULL(SUM(amount), 0) as total_income");
        Map<String, Object> incomeMap = incomeBillMapper.selectMaps(incomeWrapper).get(0);
        BigDecimal totalIncome = new BigDecimal(incomeMap.get("total_income").toString());
        result.put("totalIncome", totalIncome);
        
        // 统计支出
        QueryWrapper<ExpenseBill> expenseWrapper = new QueryWrapper<>();
        expenseWrapper.eq("status", 1); // 只统计已审核的支出
        if (StringUtils.hasText(startDate)) {
            expenseWrapper.ge("create_time", startDate);
        }
        if (StringUtils.hasText(endDate)) {
            expenseWrapper.le("create_time", endDate);
        }
        expenseWrapper.select("IFNULL(SUM(amount), 0) as total_expense");
        Map<String, Object> expenseMap = expenseBillMapper.selectMaps(expenseWrapper).get(0);
        BigDecimal totalExpense = new BigDecimal(expenseMap.get("total_expense").toString());
        result.put("totalExpense", totalExpense);
        
        // 计算利润
        BigDecimal profit = totalIncome.subtract(totalExpense);
        result.put("profit", profit);
        
        return Result.success(result);
    }

    /**
     * 导出收支项明细
     */
    @GetMapping("/exportIncomeExpenseDetails")
    public Result<String> exportIncomeExpenseDetails(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String billType,
            @RequestParam(required = false) Integer status) {

        // 暂时返回空，后续可以集成Excel导出功能
        return Result.success("导出功能待实现");
    }

    /**
     * 导出收付款明细
     */
    @GetMapping("/exportPaymentReceiptDetails")
    public Result<String> exportPaymentReceiptDetails(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String flowType,
            @RequestParam(required = false) String billType) {

        // 暂时返回空，后续可以集成Excel导出功能
        return Result.success("导出功能待实现");
    }

    /**
     * 导出利润报表
     */
    @GetMapping("/exportProfitReport")
    public Result<String> exportProfitReport(
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false) String groupBy) {

        // 暂时返回空，后续可以集成Excel导出功能
        return Result.success("导出功能待实现");
    }
}
